package org.codersunit.radboid.data;

import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class LectureList extends TreeSet<Lecture> {
	private static final long serialVersionUID = -8703747324590341056L;
	
	private int lastPosition = 0;
	private Iterator<Lecture> iteration;
	private Lecture lastLecture;
	
	public LectureList() {
		super(new LectureComparator());
	}
	
	@Override
	public boolean add(Lecture lecture) {
		lastPosition = 0;
		iteration = null;
		lastLecture = null;
		return super.add(lecture);
	}
	
	@Override
	public boolean addAll(Collection<? extends Lecture> collection) {
		lastPosition = 0;
		iteration = null;
		lastLecture = null;
		return super.addAll(collection);
	}
	
	
	public Lecture get(final int position) {
		if(position >= size()) {
			return null;
		} else {
			if(iteration == null) {
				iteration = iterator();
			} else if(lastPosition == position) {
				return lastLecture;
			} else if(lastPosition < position) {
				lastPosition = 0;
				iteration = iterator();
			}
			
			for(int i = lastPosition; i < position; i++) {
				iteration.next();
			}
			lastPosition = position;
			lastLecture = iteration.next();
			return lastLecture;
		}
	}
	
	public Calendar getStart() {
		if(size() > 0) {
			return first().getStart();
		} else {
			return null;
		}
	}
	
	public Calendar getEnd() {
		if(size() > 0) {
			return last().getEnd();
		} else {
			return null;	
		}
	}
	
	public static class LectureComparator implements Comparator<Lecture> {

		@Override
		public int compare(Lecture f, Lecture s) {
			Calendar first = f.getStart();
			Calendar second = s.getStart();
			return first.compareTo(second);
		}
		
	}
}
